import type { ProFormColumnsType } from '@/components/Pro';
import { BetaSchemaForm } from '@/components/Pro';
import {
  sysProfileControllerResetPwd,
  sysProfileControllerUpdateProfile,
} from '@/services/ess/sysProfile';
import { useIntl } from '@umijs/max';
import { message } from 'antd';
import CryptoJS from 'crypto-js/crypto-js';
import JSEncrypt from 'jsencrypt';
import React from 'react';
import { AESKey, RESKey } from './encryptKey';

const keyPair = new JSEncrypt();

interface addProps {
  handleAddSubmit: (data: any) => void;
  handleModalOpen: (data: any) => void;
  createModalOpen_parent?: boolean;
  types_operate?: string;
  userId?: string;
}

type APIComon = API.UserInfoForm | API.PasswordForm;

/**
 * AES加密
 * @param content
 * @returns {string}
 * @constructor
 */
const AESEncryption = (content: string) => {
  const aesContent = CryptoJS.enc.Utf8.parse(content);
  const key = CryptoJS.enc.Utf8.parse(AESKey.key);
  const iv = CryptoJS.enc.Utf8.parse(AESKey.iv);
  const encrypted = CryptoJS.AES.encrypt(aesContent, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.toString();
};

/**
 *RSA加密
 * @returns
 */
const encryptByRsa = (content: string) => {
  keyPair.setPublicKey(RESKey);
  return keyPair.encrypt(AESEncryption(content));
};

const AddModal: React.FC<addProps> = (props) => {
  const intl = useIntl();
  const { handleAddSubmit, createModalOpen_parent, handleModalOpen, types_operate, userId } = props;

  let columns: ProFormColumnsType<APIComon>[] = [];
  let title: string = '';
  switch (types_operate) {
    case 'userNick':
      title = intl.formatMessage({ id: 'login.m1' });
      columns = [
        {
          title: '',
          valueType: 'group',
          key: 'group1',
          colProps: { md: 24 },
          columns: [
            {
              title: intl.formatMessage({ id: 'login.m2' }),
              key: 'nickName',
              colProps: { md: 24 },
              valueType: 'text',
              dataIndex: 'nickName',
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'login.m3' }),
                  },
                  {
                    pattern: /^[\u4e00-\u9fa5a-zA-Z0-9~`!@#$%^&*()_\-+={}[\]|\\:;"'<>,.?/]{1,30}$/,
                    message: intl.formatMessage({ id: 'login.m4' }),
                  },
                ],
              },
            },
          ],
        },
      ];
      break;
    case 'changePassWord':
      title = intl.formatMessage({ id: 'login.m5' });
      columns = [
        {
          title: '',
          valueType: 'group',
          key: 'group1',
          colProps: { md: 24 },
          columns: [
            {
              title: intl.formatMessage({ id: 'login.m6' }),
              key: 'oldPassword',
              colProps: { md: 24 },
              valueType: 'password',
              dataIndex: 'oldPassword',
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'siteManage.enterPlease' }),
                  },
                ],
              },
            },
            {
              title: intl.formatMessage({ id: 'login.m7' }),
              key: 'newPassword',
              colProps: { md: 24 },
              valueType: 'password',
              dataIndex: 'newPassword',
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'siteManage.enterPlease' }),
                  },
                  {
                    pattern:
                      /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,20}$/,
                    message: intl.formatMessage({ id: 'login.m8' }),
                  },
                ],
              },
            },
            {
              title: intl.formatMessage({ id: 'login.m16' }),
              key: 'confirmPassword',
              colProps: { md: 24 },
              valueType: 'password',
              dataIndex: 'confirmPassword',
              dependencies: ['newPassword'], // 添加依赖项，当新密码改变时触发校验
              formItemProps(form) {
                return {
                  rules: [
                    {
                      required: true,
                      message: intl.formatMessage({ id: 'siteManage.enterPlease' }),
                    },
                    {
                      pattern:
                        /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,20}$/,
                      message: intl.formatMessage({ id: 'login.m8' }),
                    },
                    {
                      validator: async (_, value) => {
                        if (value && value !== form.getFieldValue('newPassword')) {
                          return Promise.reject(intl.formatMessage({ id: 'login.m9' }));
                        }
                        return Promise.resolve();
                      },
                    },
                  ],
                };
              },
            },
          ],
        },
      ];
      break;
    case 'changeEmail':
      title = intl.formatMessage({ id: 'login.m10' });
      columns = [
        {
          title: '',
          valueType: 'group',
          key: 'group1',
          colProps: { md: 24 },
          columns: [
            {
              title: intl.formatMessage({ id: 'login.email' }),
              key: 'email',
              colProps: { md: 24 },
              valueType: 'text',
              dataIndex: 'email',
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'siteManage.enterPlease' }),
                  },
                  {
                    pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
                    message: intl.formatMessage({ id: 'login.m11' }),
                  },
                ],
              },
            },
            {
              title: intl.formatMessage({ id: 'login.m12' }),
              key: 'password',
              colProps: { md: 24 },
              valueType: 'password',
              dataIndex: 'email',
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'siteManage.enterPlease' }),
                  },
                  {
                    pattern:
                      /^(?![\d]+$)(?![a-z]+$)(?![A-Z]+$)(?![~!@#$%^&*.]+$)[\da-zA-z~!@#$%^&*.]{6,20}$/,
                    message: intl.formatMessage({ id: 'login.m8' }),
                  },
                ],
              },
            },
          ],
        },
      ];
      break;
    case 'phoneNumner':
      title = intl.formatMessage({ id: 'login.m13' });
      columns = [
        {
          title: '',
          valueType: 'group',
          key: 'group1',
          colProps: { md: 24 },
          columns: [
            {
              title: intl.formatMessage({ id: 'login.m14' }),
              key: 'phone',
              colProps: { md: 24 },
              valueType: 'text',
              dataIndex: 'phone',
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'siteManage.enterPlease' }),
                  },
                  {
                    pattern: /^\d{11}$/,
                    message: intl.formatMessage({ id: 'login.m15' }),
                  },
                ],
              },
            },
            {
              title: intl.formatMessage({ id: 'login.m12' }),
              key: 'password',
              colProps: { md: 24 },
              valueType: 'password',
              dataIndex: 'email',
              formItemProps: {
                rules: [
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'siteManage.enterPlease' }),
                  },
                  {
                    pattern:
                      /^(?![\d]+$)(?![a-z]+$)(?![A-Z]+$)(?![~!@#$%^&*.]+$)[\da-zA-z~!@#$%^&*.]{6,20}$/,
                    message: intl.formatMessage({ id: 'login.m8' }),
                  },
                ],
              },
            },
          ],
        },
      ];
      break;
  }

  return (
    <BetaSchemaForm<APIComon>
      title={title}
      grid={true}
      labelCol={{
        flex: `0 0 100px`,
      }}
      colProps={{ md: 12 }}
      layoutType="ModalForm"
      open={createModalOpen_parent}
      onOpenChange={handleModalOpen}
      layout="horizontal"
      columns={columns}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => console.log('run'),
        width: '600px',
      }}
      submitTimeout={100}
      onFinish={async (values) => {
        if (types_operate === 'changePassWord') {
          let result = await sysProfileControllerResetPwd({
            ...values,
            userId,
            oldPassword: encryptByRsa(values.oldPassword),
            newPassword: encryptByRsa(values.newPassword),
            confirmPassword: encryptByRsa(values.confirmPassword),
          });
          console.log(result);
          if (result.code === 200) {
            message.success(intl.formatMessage({ id: 'global.addSuccessfully' }));
            handleAddSubmit(true);
          }
          handleModalOpen(false);
        } else {
          let result;
          if (types_operate === 'changeEmail' || types_operate === 'phoneNumner') {
            result = await sysProfileControllerUpdateProfile({
              ...values,
              userId,
              password: encryptByRsa(values.password),
            });
          } else {
            result = await sysProfileControllerUpdateProfile({ ...values, userId });
            console.log(result);
          }

          if (result?.code === 200) {
            message.success(intl.formatMessage({ id: 'global.addSuccessfully' }));
            handleAddSubmit(true);
          }
          handleModalOpen(false);
        }

        return true;
      }}
    ></BetaSchemaForm>
  );
};

export default AddModal;
